package com.ruoyi.project.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.HttpClients;
import com.ruoyi.common.utils.Maps;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysOrder;
import com.ruoyi.project.system.domain.SysOrderDetail;
import com.ruoyi.project.system.es.SysDeptRepository;
import com.ruoyi.project.system.service.ICartService;
import com.ruoyi.project.system.service.SysOrderDetailService;
import com.ruoyi.project.system.service.SysOrderService;
import io.netty.handler.codec.http.HttpRequest;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import test.util.SequenceUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Service
public class CartServiceImpl implements ICartService{

    @Autowired
    private SysDeptRepository sysDeptRepository;

    @Autowired
    private SysOrderService sysOrderService;

    @Autowired
    private SysOrderDetailService sysOrderDetailService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;



    @Override
    @Transactional
    public AjaxResult checkData(Map data) {
        Map resultMap=new HashMap();
        SysDept dept=sysDeptRepository.findById(Integer.valueOf(data.get("deptId").toString())).get();;
        resultMap.putAll(getDistance(data.get("geohash").toString(), dept.getLat() + "," + dept.getLng()));
        resultMap.putAll(Maps.newHashMap("status_text", "不需要开发票", "is_available", true));
        resultMap.put("DeptId",dept.getDeptId());
        resultMap.put("deptInfo",dept);
        List<List> entities = (List<List>) data.get("entities");
        List<Map> groups = Lists.newArrayList();
        //商品总金额
        BigDecimal foodTotal = new BigDecimal(0);
        //包装费
        BigDecimal packingTotal = new BigDecimal(0);
        for (int i = 0; i < entities.get(0).size(); i++) {
            Map map = (Map) entities.get(0).get(i);
            Map items = Maps.newHashMap();
            items.put("foodId", Long.valueOf(map.get("foodId").toString()));
            items.put("name", map.get("name"));
            items.put("specId", map.get("specId"));
            items.put("specs", map.get("specs"));
            items.put("packing", map.get("packing"));
            items.put("price", map.get("price"));
            items.put("num", map.get("num"));
            packingTotal=packingTotal.add(new BigDecimal(items.get("packing").toString()).multiply(new BigDecimal(items.get("num").toString())));
            foodTotal = foodTotal.add(new BigDecimal(items.get("price").toString()).multiply(new BigDecimal(items.get("num").toString())));
            groups.add(items);
        }
        resultMap.put("foodTotal",foodTotal);
        resultMap.put("floatDeliveryFee",dept.getFloatDeliveryFee());
        resultMap.put("packingTotal",packingTotal);
        resultMap.put("orderTotal",foodTotal.add(packingTotal).add(new BigDecimal(dept.getFloatDeliveryFee())));
        resultMap.put("groups",groups);
        List<Map> payments=new ArrayList<>();

        Map map1=new HashMap<>();
        map1.put("description","");
        map1.put("disabledReason","");
        map1.put("id","2");
        map1.put("isOnlinePayment",true);
        map1.put("name","支付宝");
        map1.put("selectState",1);
        Map map2=new HashMap<>();
        map2.put("description","");
        map2.put("disabledReason","");
        map2.put("id","1");
        map2.put("isOnlinePayment",true);
        map2.put("name","微信");
        map2.put("selectState",-1);
        payments.add(map1);
        payments.add(map2);
        resultMap.put("payments",payments);
        resultMap.put("id",1);
        resultMap.put("sign",1);
        resultMap.putAll(Maps.newHashMap("statusText", "不需要开发票", "isAvailable", true));
        return AjaxResult.success(resultMap);
    }

    @Override
    @Transactional
    public AjaxResult createOrder(Map data) {
        SysOrder sysOrder=new SysOrder();
        Map orderData= (Map) data.get("orderData");
        Map deptInfo= (Map) orderData.get("deptInfo");
        Map address= (Map) data.get("address");
        sysOrder.setUserId( SecurityUtils.getLoginUser().getUser().getUserId());
        sysOrder.setDeptId(Long.valueOf(deptInfo.get("deptId")+""));
        sysOrder.setPayStatus("1");
        sysOrder.setOrderNo(SequenceUtils.getCurentDate()+SequenceUtils.getSequence(redisTemplate.opsForValue().increment("serial.number:" + SequenceUtils.getCurentDate())));
        sysOrder.setOrderTotal(Double.valueOf(orderData.get("orderTotal")+""));
        sysOrder.setFoodTotal(Double.valueOf(orderData.get("foodTotal")+""));
        sysOrder.setPackingTotal(Double.valueOf(orderData.get("packingTotal")+""));
        sysOrder.setFloatDeliveryFee(Double.valueOf(deptInfo.get("floatDeliveryFee")+""));
        sysOrder.setMoney(Double.valueOf(orderData.get("orderTotal")+""));
        sysOrder.setName(address.get("name")+"");
        sysOrder.setGeohash(address.get("geohash")+"");
        sysOrder.setPhone(address.get("phone")+"");
        sysOrder.setAddress(address.get("address")+"");
//        sysOrder.setCreateTime(new Date());
        sysOrder.setCreateBy(SecurityUtils.getUsername());
        if(null!=address.get("remark")){
            sysOrder.setRemark(address.get("remark")+"");
        }
        sysOrderService.insert(sysOrder);
        List<SysOrderDetail> orderDetails = JSONObject.parseArray(JSON.toJSONString( orderData.get("groups")), SysOrderDetail.class);
        for(SysOrderDetail orderDetail:orderDetails){
            orderDetail.setOrderId(sysOrder.getOrderId());
            sysOrderDetailService.insert(orderDetail);
        }
        MessagePostProcessor messagePostProcessor = message -> {
            MessageProperties messageProperties = message.getMessageProperties();
//            设置编码
            messageProperties.setContentEncoding("utf-8");
//            设置过期时间10*1000毫秒(最终过期时间取x-message-ttl和messageProperties.setExpiration的最小值
            messageProperties.setExpiration("900000");
//            messageProperties.setExpiration("60000");
            return message;
        };
        rabbitTemplate.convertAndSend("DL_EXCHANGE", "DL_KEY", sysOrder.getOrderId(),messagePostProcessor);
        return AjaxResult.success(sysOrder);
    }




    protected HttpServletRequest getRequest(){
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        return sra.getRequest();
    }


    public static Map<String,String> getDistance(String from, String to){
        Map<String,String> params = Maps.newHashMap("ak", RuoYiConfig.getBaiduKey(),"output","json", "origins",from,"destinations",to);
        try {
            //使用百度地图api获取距离值：
            //routematrix/v2/riding 骑行
            //routematrix/v2/driving 开车
            //routematrix/v2/walking 步行
            String str = HttpClients.get(RuoYiConfig.getBaiduApiUrl() + "routematrix/v2/riding", params);
            JSONObject response =  JSONObject.parseObject(str);
            if("0".equals(response.get("status").toString())){
                JSONArray array=response.getJSONArray("result");
                Map result =  Maps.newHashMap(
                        "distance",array.getJSONObject(0).getJSONObject("distance").getString("text"),
                        "duration",array.getJSONObject(0).getJSONObject("duration").getString("text")
                );
                return result;
            }else{
                throw new BaseException("获取送达时间报错");
            }

        }catch (Exception e){
            throw new BaseException("获取送达时间报错");
        }
    }

    public static void main(String[] args) {
        Map<String,String> map=getDistance(32.033651+","+118.736207,32.033651+","+118.736207);
    }

}
